declare const Buffer: any;

export type SignatureRecord = {
  signaturePath: string;
  signatureName: string;
  sourcePath: string;
  createdAt: string;
  deviceLabel: string;
  deviceSN: string;
  certSubject: string;
  certAlgorithm: string;
};

const SIG_META_SUFFIX = ".zjsigmeta.json";

const getMetaPath = (signaturePath: string) =>
  signaturePath ? `${signaturePath}${SIG_META_SUFFIX}` : "";

const stringifyRecord = (record: SignatureRecord) =>
  JSON.stringify(record, null, 2);

export const saveSignatureMeta = (
  zjca: any,
  signaturePath: string,
  record: SignatureRecord
): { ok: boolean; path: string; message?: string } => {
  if (!zjca || typeof zjca.writeFile !== "function") {
    return { ok: false, path: "", message: "SDK 未提供 writeFile 接口" };
  }
  const metaPath = getMetaPath(signaturePath);
  if (!metaPath) return { ok: false, path: "", message: "无效的签名路径" };
  try {
    const resp = zjca.writeFile(metaPath, stringifyRecord(record), false);
    if (resp && typeof resp.code === "number" && resp.code !== 0) {
      return { ok: false, path: metaPath, message: resp.msg || `${resp.code}` };
    }
    return { ok: true, path: metaPath };
  } catch (error: any) {
    return { ok: false, path: metaPath, message: error?.message || String(error) };
  }
};

const decodeBase64 = (raw: string) => {
  if (typeof window !== 'undefined' && typeof window.atob === 'function') {
    return window.atob(raw);
  }
  if (typeof Buffer !== 'undefined') {
    return Buffer.from(raw, 'base64').toString('utf-8');
  }
  throw new Error('当前环境不支持 Base64 解码');
};

const parseRecord = (raw: string) => {
  try {
    return JSON.parse(raw);
  } catch (error) {
    try {
      return JSON.parse(decodeBase64(raw));
    } catch (inner) {
      throw inner;
    }
  }
};

export const readSignatureMeta = (
  zjca: any,
  signaturePath: string
): SignatureRecord | null => {
  if (!signaturePath || !zjca || typeof zjca.readFile !== "function") return null;
  const metaPath = getMetaPath(signaturePath);
  if (!metaPath) return null;
  try {
    const resp = zjca.readFile(metaPath, false);
    if (resp?.code !== 0 || !resp.res) return null;
    return parseRecord(resp.res);
  } catch (error) {
    console.warn("读取签名元数据失败:", error);
    return null;
  }
};
